/*
 * Copyright (c) 2015. kupat Corporation. All rights reserved.
 *  see statement on http://www.kupat.cn.
 */
package com.kfgj.hkp.common.utils;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Created by liwensihan on 2014/11/27.
 *
 * @author liwensihan
 */
public class ValidationUtils {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static ValidationResult validate(Object obj, String... propertyNames) {//验证某一个对象

        StringBuffer buffer = new StringBuffer();//用于存储验证后的错误信息

        if (propertyNames == null || propertyNames.length < 1) {
            loadMessage(validator.validate(obj), buffer);
        } else {
            for (String prop : propertyNames) {
                loadMessage(validator.validateProperty(obj, prop), buffer);
            }
        }

        ValidationResult result = new ValidationResult();

        result.setSuccess(buffer.length() > 0 ? Boolean.FALSE : Boolean.TRUE);
        result.setMessage(buffer.toString());

        return result;
    }

    private static void loadMessage(Set<ConstraintViolation<Object>> crv, StringBuffer buffer) {

        for (ConstraintViolation<Object> cv : crv) {
            buffer.append(cv.getMessage()).append(",");
        }
    }

}
